import { RootThunkAction, HomeAction, Article } from "@/types/store";
import http from '@/utils/http'
import { Channel } from "@/types/store";
import { ApiResponse } from "@/types/data";
import { getChannels, hasToken, setChannels } from "@/utils/storage";
export function getUserChannel(): RootThunkAction {
  return async (dispatch) => {
    // 判断是否登录
    if (hasToken()) {
      // 登录了 就获取用户的频道
      const res = await http.get<ApiResponse<{ channels: Channel[] }>>(
        '/user/channels'
      )
      console.log(res);

      dispatch({
        type: 'home/getUserChannel',
        payload: res.data.data.channels,
      })
    } else {
      // 没有登录，优先从本地获取
      const channels = getChannels()
      if (channels.length > 0) {
        // 本地有数据
        dispatch({
          type: 'home/getUserChannel',
          payload: channels,
        })
      } else {
        // 本地没有数据，且本地没有数据
        const res = await http.get<ApiResponse<{ channels: Channel[] }>>(
          '/channels'
        )
        dispatch({
          type: 'home/getUserChannel',
          payload: res.data.data.channels,
        })
        // 存储到本地
        setChannels(res.data.data.channels)
      }
    }
  }
}

/**
 * 获取所有频道的数据
 * @returns
 */
export function getAllChannel(): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiResponse<{ channels: Channel[] }>>(
      '/channels'
    )
    dispatch({
      type: 'home/getAllChannels',
      payload: res.data.data.channels
    })
  }
}

/**
 * 修改高亮的方法
 * @param id
 * @returns
 */
export function changeActive(id: number): HomeAction {
  return {
    type: 'home/changeActive',
    payload: id
  }
}

// 添加频道
export const addChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    // 获取到所有的userChannels
    const { userChannels } = getState().home
    // 如果登录了，发送请求获取频道信息
    if (hasToken()) {
      await http.patch('/user/channels', {
        channels: [channel],
      })
    } else {
      // 如果没有登录，将频道数据保存到本地
      // 将channels数据保存本地
      setChannels([...userChannels, channel])
    }
    // 然后继续重新获取channel
    // dispatch({
    //   type: 'home/getUserChannel',
    //   payload: [...userChannels, channel],
    // })
    dispatch(getUserChannel())
  }
}

// 删除频道
export function delChannel(id: number): RootThunkAction {
  return async (dispatch, getState) => {
    const { userChannels } = getState().home
    if (hasToken()) {
      // 如果登录了那就直接删除
      await http.delete('/user/channels', {
        data: {
          channels: [id]
        }
      })
    } else {
      // 如果没登录，那就在本地删除
      setChannels(
        userChannels.filter(item => item.id !== id)
      )
    }
    dispatch(getUserChannel())
  }
}

/**
 * 获取文章列表
 * @param channel_id 获取文章列表
 * @param timestamp 时间戳
 * @returns
 */
export const getArticleList = (
  channel_id: number,
  timestamp: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await http.get<
      ApiResponse<{
        pre_timestamp: string
        results: Article[]
      }>
    >('/articles', {
      params: {
        channel_id,
        timestamp,
      },
    })
    console.log(res)
    const { pre_timestamp, results } = res.data.data
    console.log(pre_timestamp, '============================================================旧的时间戳');
    dispatch({
      type: 'home/saveChannelArticles',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results,
      },
    })
  }
}

export const getNewList = (
  channel_id: number,
  timestamp: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await http.get<
      ApiResponse<{
        pre_timestamp: string
        results: Article[]
      }>
    >('/articles', {
      params: {
        channel_id,
        timestamp,
      },
    })
    const { pre_timestamp, results } = res.data.data
    dispatch({
      type: 'home/saveNewArticles',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results,
      },
    })
  }
}